package com.crm.customers.controller; 

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.crm.base.controller.BaseController;
import com.crm.customers.model.Article;
import com.crm.customers.model.Commission;
import com.crm.customers.model.CommissionCustomer;
import com.crm.customers.model.ContactsDynamicInfo;
import com.crm.customers.model.Contract;
import com.crm.customers.model.ContractMoneylog;
import com.crm.customers.model.CustomerCategory;
import com.crm.customers.model.CustomerClaim;
import com.crm.customers.model.CustomerContacts;
import com.crm.customers.model.CustomerFiles;
import com.crm.customers.model.CustomerInfo;
import com.crm.customers.model.CustomerRecyclebin;
import com.crm.customers.service.ArticleService;
import com.crm.customers.service.CommissionCustomerService;
import com.crm.customers.service.CommissionService;
import com.crm.customers.service.ContactsDynamicInfoService;
import com.crm.customers.service.ContractMoneylogService;
import com.crm.customers.service.ContractService;
import com.crm.customers.service.CustomerCategoryService;
import com.crm.customers.service.CustomerClaimService;
import com.crm.customers.service.CustomerContactsService;
import com.crm.customers.service.CustomerFilesService;
import com.crm.customers.service.CustomerRecyclebinService;
import com.crm.customers.service.CustomerService;
import com.crm.sys.model.ConfigureItem;
import com.crm.sys.model.FilesInfo;
import com.crm.sys.model.Log;
import com.crm.sys.model.Province;
import com.crm.sys.service.FilesInfoService;
import com.crm.sys.service.SysService;
import com.crm.user.model.UserAccount;
import com.crm.user.model.UserInfo;
import com.crm.user.service.UserService;
import com.crm.util.CommonUtil;
import com.crm.util.Constants;
import com.crm.util.CrmUtil;
import com.crm.util.Pager;
import com.crm.util.XLSUtil;

/**
 * 客户管理Controller
 * */
@Controller
public class MCustomerController extends BaseController {
	
	@Autowired
	private CustomerService customerService;
	
	@Autowired
	private ContactsDynamicInfoService contactsDynamicInfoService;
	
	@Autowired
	private CustomerContactsService customerContactsService;
	
	@Autowired
	private SysService sysService;
	
	@Autowired
	private FilesInfoService filesInfoService;
	
	@Autowired
	private CustomerFilesService customerFilesService;
	
	@Autowired
	private CustomerCategoryService CustomerCategoryService;
	
	@Autowired
	private UserService userService;
	@Autowired
	private ContractMoneylogService contractMoneylogService;
	@Autowired
	private ContractService contractService;
	@Autowired
	private CustomerClaimService customerClaimService;
	@Autowired
	private CustomerRecyclebinService customerRecyclebinService;
	@Autowired
	private CommissionService commissionService;
	@Autowired
	private CommissionCustomerService commissionCustomerService;
	@Autowired
	private ArticleService articleService;
	
	 
	/**
	 * 参数转换<br>
	 * 将K中的参数取出放入map集合中
	 * */
	private static Map<String, Object> toBean(String k) {
		//ty{客户类型}_p{页码}_so{排列方式}_st{客户状态（所在库）}_c{城市}?kwd={关键字}
		Map<String, Object> map = new HashMap<String, Object>();
		String[] key = k.split("_");
		for (String ks : key) {
			if (ks.indexOf("ty")>-1){
				try{
					map.put("ty", Integer.parseInt(ks.replace("ty", "")));
				}catch(Exception e){}	
			} else if (ks.indexOf("p")>-1) {
				try{
					map.put("p", Integer.parseInt(ks.replace("p", "")));
				}catch(Exception e){}
			}  else if (ks.indexOf("so")>-1) {
				try{
					map.put("so", ks.replace("so", ""));
				}catch(Exception e){}
			}  else if (ks.indexOf("st")>-1) {
				try{
					map.put("st", Integer.parseInt(ks.replace("st", "")));
				}catch(Exception e){}
			} else if (ks.indexOf("ro")>-1) {
				try{
					map.put("ro", ks.replace("ro", ""));
				}catch(Exception e){}
			}  else if (ks.indexOf("c")>-1) {
				try{
					map.put("c", ks.replace("c", ""));
				}catch(Exception e){}
			} else if (ks.indexOf("at")>-1) {
				try{
					map.put("at", ks.replace("at", ""));
				}catch(Exception e){}
			} 
		}
		return map;
	}
	/**
	 * 企业管理页面<br>
	 * 根据参数K查询对应的customer列表<br>
	 * 根据state决定跳转到哪个页面<br>
	 * */
	@RequestMapping("/m/customer/entman/{k}")
	public String intoEnterpriseManagePage(@PathVariable String k,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception {
		UserAccount ua = getLoginUser();
		//创建一个Customer对象来接收参数
		CustomerInfo ci = new CustomerInfo();
		//获取参数集合
		Map<String, Object> map = toBean(k);
		//获取页码，定义每页显示多少（根据state决定）
		Integer pageNo = map.get("p") == null ? 1 : (Integer)map.get("p");
		Integer pageSize = 10;
		//给ci赋值
		ci.setType((Integer)map.get("ty"));
		if (!Strings.isNullOrEmpty((String)map.get("so"))){
			ci.setSort((String)map.get("so"));
		} else {
			ci.setSort("0");
		}
		if (map.get("st")!=null && map.get("st")!=""){
			ci.setState((Integer)map.get("st"));
		}
		if (map.get("at")!=null && map.get("at")!=""){
			ci.setCategory((String)map.get("at"));
		}
		ci.setCity((String)map.get("c"));
		ci.setProvince((String)map.get("ro"));
		if(request.getParameter("kwd")!=null){  
			ci.setKeyWord(URLDecoder.decode(URLDecoder.decode(request.getParameter("kwd"), "UTF-8"),"UTF-8"));
		}
		
		if(request.getParameter("address")!=null){  
			ci.setAddress(URLDecoder.decode(URLDecoder.decode(request.getParameter("address"), "UTF-8"),"UTF-8"));
		}
		
		//ci赋值uid
		ci.setUid(ua.getId());
		//根据ci中的条件获取列表
		Pager pager = customerService.getCustomerInfoList(ci, pageNo, pageSize);
		pager.setUrl("/m/customer/entman/" + k);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("KeyWord", ci.getKeyWord());
		params.put("sort",ci.getSort());
		params.put("city", ci.getCity());
		params.put("address", ci.getAddress());
		params.put("province", ci.getProvince());
		params.put("state", ci.getState());
		params.put("category", ci.getCategory());
		//要是有其他参数要继续往下添加
		pager.setParams(params);
		request.setAttribute("pager", pager);
		//我把企业和人才的相同的页面写到一起了，传到页面一个type来区分
		request.setAttribute("customertype", ci.getType());
		request.setAttribute("customerstate", ci.getState()); 
		
		request.setAttribute("list", JSONArray.toJSONString(pager.getResultList()));
		//这里要根据state和type判断要跳转到哪个页面
		if (ci.getType() == 1) {
			return MOBILEPATH+"/customermanage/customerlist";
		} else {
			return MOBILEPATH+"/resumemanage/resumelist";
		}
		/*Map<String, Object> map = toBean(k);
		if ((Integer)map.get("ty") == 1) {
			return "mobile/customermanage/customerlist";
		} else {
			return "mobile/resumemanage/resumelist";
		}*/
	}
	
	
	 
	@RequestMapping(value="/m/customer/list", produces="text/html;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public String EnterpriseManageDataAjax(@ModelAttribute CustomerInfo ci,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes) throws Exception {
		UserAccount ua = getLoginUser();
	  
		//获取页码，定义每页显示多少（根据state决定）
		Integer pageNo = getSkipToPage();
		Integer pageSize = 10; 
		//ci赋值uid
		ci.setUid(ua.getId());
		ci.setSort("0");
		//根据ci中的条件获取列表
		Pager pager = customerService.getCustomerInfoList(ci, pageNo, pageSize);
		return JSONArray.toJSONString(pager.getResultList());
	}
	
	/**
	 * 查看客户详情
	 * {k}为客户id
	 * */
	@RequestMapping(value="/m/customer/updatecustomer{k}")
	public String intoAddCustomerPage(@PathVariable String k,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		//先要获取信息表的id
		Long id = Long.parseLong(k);
		//然后就是根据信息表id获取信息详情了（里面包含了联系人表）
		CustomerInfo ci = customerService.getCustomerInfoById(id);
		request.setAttribute("ci", ci);
		request.setAttribute("id", id);
		if (ci.getType() == 1) {
			return MOBILEPATH+"/customermanage/entercustomer";
		} else {
			return MOBILEPATH+"/resumemanage/enterresume";
		}
	}
	
	/**
	 * 修改客户信息
	 * */
	@RequestMapping(value="/m/customer/updatecustomer", produces="text/html;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public String updateCustomerInfo(@ModelAttribute CustomerInfo ci,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		//直接保存
		customerService.saveCustomerInfo(ci);
		return JSON.toJSONString(0);
	}
	
	
	
	
	/**
	 * 根据id获取用户详情
	 * */
	@RequestMapping(value="/m/customer/customerinfo", produces="text/html;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public String getCustomerInfo(@ModelAttribute CustomerInfo ci,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		ci = customerService.getCustomerInfoById(ci.getId());
		return JSON.toJSONString(ci);
	}
	
	/**
	 * 获取和放弃客户
	 * */
	@RequestMapping(value="/m/customer/hqfqcustomer",produces="text/html;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public String HqAndFqCustomer(String type,String id,Integer sign,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		
		//获取用户详情
		CustomerInfo ci = customerService.getCustomerInfoById(Long.parseLong(id));
		ci.setUpdateuser(getLoginUser().getId());
		//日志记录
		Log log = new Log();
		log.setContentid(ci.getId());
		log.setCreateuser(ci.getUpdateuser());
		log.setUid(ci.getUpdateuser());
		log.setOid(ci.getUpdateuser());
		//根据sign来区分是获取还是
		if (sign == 0) {
			//获取
			ci.setUid(getLoginUser().getId());
			ci.setState(1);
			//判断是否超过获取上限
			int resourceCount = customerService.getResourceCount(ci);
			if (Integer.parseInt(type) == 1 && resourceCount >= getLoginUser().getInfo().getMaxresume()) {
				return JSON.toJSONString(-1);
			}
			if (Integer.parseInt(type) == 0 && resourceCount >= getLoginUser().getInfo().getMaxresume()) {
				return JSON.toJSONString(-1);
			}
			//判断是企业还是人才后保存到log
			if (Integer.parseInt(type)==0) {
				log.setDescription("获取人才客户"+ci.getCname());
				log.setCategory(Constants.LOGCATEGORY.ZERO);
			} else {
				log.setDescription("获取企业客户"+ci.getCname());
				log.setCategory(Constants.LOGCATEGORY.ONE);
			}
    		log.setState(Constants.LOGSTATE.ZERO);
    		//保存记录和修改
    		customerService.updateCustomerState(ci,log);
		} else {
			//放弃
			ci.setUid(null);
			ci.setState(4);
			
			//判断是企业还是个人,如果是企业,可以直接删除,如果是个人,要看是否有合同,如果有合同,就不能被删除
			if (Integer.parseInt(type) == 0) {
				log.setDescription("放弃个人客户"+ci.getCname());
				log.setCategory(Constants.LOGCATEGORY.ZERO);
				//人才这里要加是否有合同判断
				int result = contractService.checkResurmeHaveContract(ci.getId());
				if (result > 0) {
					return JSON.toJSONString(2);
				}
			} else {
				log.setDescription("放弃企业客户"+ci.getCname());
				log.setCategory(Constants.LOGCATEGORY.ONE);
			}
			log.setState(Constants.LOGSTATE.ONE);
            customerService.updateCustomerState(ci,log);
		}
		return JSON.toJSONString(0);
	}
	
	/**
	 * 回收客户资源
	 * */
	@RequestMapping(value="/m/customer/recyclebinsave",produces="text/html;charset=UTF-8", method = RequestMethod.POST)
	@ResponseBody
	public String saveRecyclebin(String id,HttpServletResponse response,HttpServletRequest request,
			RedirectAttributes redirectAttributes){
		CustomerRecyclebin cr = new CustomerRecyclebin();
		cr.setCusid(Long.parseLong(id));
		int  i = customerRecyclebinService.saveCustomerRecyclebin(cr);
		return JSONArray.toJSONString(i);
	}
	
	
}
